/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2017 All Rights Reserved.
 */
package com.fulihui.usercore.algorithm;

import io.shardingsphere.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * usr_wechat_user(用户授权信息) 表分表策略，根据userid分
 * @author: zhangyingjie
 * @version: v 0.1 2017年10月16日 15:22  zhangyingjie Exp $
 */
public class TbUsrWechatUserShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    protected final transient Logger LOGGER = LoggerFactory.getLogger(getClass());
    private final int TABLE_COUNT = 20;

    private final String DEFAULT_TABLE = "usr_wechat_user";
    /**
     * 分表策略，根据userid的hash值 跟TABLE_COUNT进行取余
     * @param tablenames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> tablenames, PreciseShardingValue<String> shardingValue) {
        Integer suffix = Math.abs(
                new HashCodeBuilder().append(shardingValue.getValue()).hashCode() % TABLE_COUNT);
        for (String each : tablenames) {
            if (each.endsWith("_" + suffix)) {
                return each;
            }
        }
        LOGGER.info("TbUsrWechatUserShardingAlgorithm,没有路由到表，shardingValue：{}",shardingValue.getValue());
        return DEFAULT_TABLE;
    }
}
